package com.liuheng.manager.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuheng.manager.mapper.SysUserMapper;
import com.liuheng.manager.service.SysUserService;
import com.liuheng.manager.utils.MenuHelper;
import com.liuheng.spzx.model.entity.system.SysMenu;
import com.liuheng.spzx.model.entity.system.SysUser;
import com.liuheng.spzx.model.vo.system.SysMenuVo;
import com.liuheng.util.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements SysUserService {

@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SysUserMapper sysUserMapper;
    @Override
    public SysUser getUserInfo(String token) {
        SysUser user= (SysUser) redisTemplate.opsForValue().get("user:login" + token);
        return user;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public List<SysMenuVo> findUserMenuList() {
        SysUser user = AuthContextUtil.getUser();
        Long userId = user.getId();
        ArrayList<SysMenu> sysMenuList= (ArrayList<SysMenu>) sysUserMapper.selectListByUserId(userId);
        List<SysMenu> sysMenuTree = MenuHelper.getTree(sysMenuList);
        return this.buildMenus(sysMenuTree);
    }
    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {

        List<SysMenuVo> sysMenuVoList = new LinkedList<SysMenuVo>();
        for (SysMenu sysMenu : menus) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());
            List<SysMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;
    }
}
